package com.sercomm.ott.mediaplayer;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.format.Formatter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.net.wifi.ScanResult;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sercomm.ott.mediaplayer.fragment_test.*;
import com.sercomm.ott.mediaplayer.viewpager_test.*;


/**
 * Created by davis on 17-8-25.
 */

public class WifiActivity extends Activity implements View.OnClickListener{
    private static final String TAG = "wifitest";
    private static final String KEY_ONSAVEINSTANCESTATE = "onSaveInstanceState";
    //private TextView mScanList;
    private ListView scan_list_info=null;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ArrayList<HashMap<String, String>> scanitems;
    private SimpleAdapter scanadapter;
    private static final String[] SCAN_INFO_LIST = new String[]{"ssid", "capabilities","dbm"};
    private static final int[] SCAN_INFO_LIST_RES = new int[]{R.id.scan_info_ssid,R.id.scan_info_dbm,R.id.scan_info_capabilities};

    private static final String[] WIFI_INFO_LIST = new String[]{"name", "detail"};
    private static final int[] WIFI_INFO_LIST_RES = new int[]{R.id.wifi_info_name, R.id.wifi_info_detail};
    private ListView wifi_list_info = null;
    private int select_item;
    private WifiUtils mWifiUtils;
    private WifiManager wifi_service = null;
    WifiInfo wifiinfo = null;
    DhcpInfo dhcpinfo = null;
    private IntentFilter mWifiStateFilter=null;
    WifiConfiguration wifiConfiguration = null;
    List<WifiConfiguration> wifiConfigList=null;


    private BluetoothManager bluetoothManager = null;
    private BluetoothAdapter bta = null;

    PopupMenu pop;
    private Button btn_popmenu;

    private Button btn_contextmenu;
    private TextView tv_contextmenu;

    private ExpandableListView expandableListView;
    List<Map<String,String>> groups = new ArrayList<Map<String,String>>();
    List<List<Map<String, String>>> childs = new ArrayList<List<Map<String, String>>>();


    Intent myWifiService =null;

    ContentResolver resolver = null;
    private String ntp_server = null;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    private final BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)){
                int mess=intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,-1);
                LogUtil.d(TAG,"--------wifi changed mess is "+mess);
                Log.d(TAG,"-----davis wifi state changed action");
                //Toast.makeText(WifiActivity.this,"wifi state changed action",Toast.LENGTH_SHORT).show();
            }
            else if(intent.getAction().equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)){
                Log.d(TAG,"------davis supplicant connection changed action");
                //Toast.makeText(WifiActivity.this,"supplicant connection change action",Toast.LENGTH_SHORT).show();
            }else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
                Log.d(TAG,"------davis network state  changed action");
                //Toast.makeText(WifiActivity.this,"network state changed action",Toast.LENGTH_SHORT).show();
            }

        }
    };
    public static class MyBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context,Intent intent){
            Toast.makeText(context,"received MyBroadcastReceiver",Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wifi_test);

        resolver = getApplicationContext().getContentResolver();
        ntp_server = Settings.Global.getString(resolver,"ntp_server");

        wifi_list_info = (ListView) findViewById(R.id.wifi_info_list);
        scan_list_info = (ListView) findViewById(R.id.scan_list);
        wifi_service = (WifiManager) getSystemService(WIFI_SERVICE);
        wifiinfo = wifi_service.getConnectionInfo();
        dhcpinfo = wifi_service.getDhcpInfo();
        scanitems = new ArrayList<>();
        scanadapter = new SimpleAdapter
                (this, scanitems, R.layout.scan_list, SCAN_INFO_LIST, SCAN_INFO_LIST_RES);
        scan_list_info.setAdapter(scanadapter);
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.srl);
        swipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.BLACK);
        swipeRefreshLayout.setColorSchemeColors(Color.BLUE);
        swipeRefreshLayout.measure(0,0);
        swipeRefreshLayout.setRefreshing(true);
        initSwipeRefresh();
        initSwipeData();

        Button btn_munu = (Button) findViewById(R.id.menu_button);

        myWifiService = new Intent(this,WifiService.class);
        btn_popmenu = (Button) findViewById(R.id.popmenu_button);
        btn_popmenu.setOnClickListener(WifiActivity.this);
        setPopupMenu(btn_popmenu);

        btn_contextmenu = (Button) findViewById(R.id.contextmenu_button);
        btn_contextmenu.setOnClickListener(WifiActivity.this);
        registerForContextMenu(btn_contextmenu);

        expandableListView =(ExpandableListView)findViewById(R.id.expandable_list_view);
        expandableFun();

        tv_contextmenu = (TextView) findViewById(R.id.contextmenu_tv);
        tv_contextmenu.setFocusable(true);
        tv_contextmenu.setOnClickListener(WifiActivity.this);
        registerForContextMenu(tv_contextmenu);

        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bta = bluetoothManager.getAdapter();

        //wifi_service = (WifiManager) getSystemService(WIFI_SERVICE);
        //wifiinfo = wifi_service.getConnectionInfo();
        //dhcpinfo = wifi_service.getDhcpInfo();


        mWifiStateFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mWifiStateFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        mWifiStateFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mWifiStateFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mWifiStateFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        mWifiStateFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        mWifiStateFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(mWifiStateReceiver,mWifiStateFilter);




        Log.d(TAG , "-----davis  Security Start");
        wifiConfigList = wifi_service.getConfiguredNetworks();
        /*
        for (WifiConfiguration wifiConfiguration : wifiConfigList) {
            //配置过的SSID
            String configSSid = wifiConfiguration.SSID;
            configSSid = configSSid.replace("\"", "");

            //当前连接SSID
            String currentSSid =wifiinfo.getSSID();
            currentSSid = currentSSid.replace("\"", "");

            //比较networkId，防止配置网络保存相同的SSID
            if (currentSSid.equals(configSSid) && wifiinfo.getNetworkId()==wifiConfiguration.networkId) {
                Log.d(TAG, "------davis-----当前网络安全性：" + getSecurity(wifiConfiguration));
            }
        }
        */

        //Context context = this.getApplicationContext();
        //mWifiUtils = new WifiUtils(context);


        try {
            final ArrayList<HashMap<String, String>> items = getInfo(mWifiUtils);
            final SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.wifi_list, WIFI_INFO_LIST, WIFI_INFO_LIST_RES);
            wifi_list_info.setAdapter(adapter);
            wifi_list_info.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    HashMap<String, String> map = items.get(i);
                    if (map.get("name").equals("connection status")) {
                        Intent wifiSettingIntent = new Intent();
                        wifiSettingIntent.setComponent(new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings"));
                        startActivity(wifiSettingIntent);
                        //Toast.makeText(WifiActivity.this, map.get("name") + map.get("detail"), Toast.LENGTH_LONG).show();
                    }
                }

            });
        }catch (Exception e){
            e.printStackTrace();
        }


        scan_list_info.setNextFocusDownId(R.id.menu_button);
        expandableListView.setNextFocusUpId(R.id.contextmenu_tv);

        /*
        wifi_list_info.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

            }
        });
        */

        setListData();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

        sharedfile();
        SystemStatus.initSystemManager(this);

        if(savedInstanceState!=null){
            String saveState = savedInstanceState.getString(KEY_ONSAVEINSTANCESTATE,"oh no");
            Log.d(TAG,"-------davis-----onSaveInstanceState test is "+saveState);
        }

    }

    private void initSwipeRefresh(){
        Log.d(TAG,"-----swipe refresh");
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initSwipeData();
            }
        });

    }
    private void initSwipeData(){
        try {
            scanitems=getScanInfo();
            scanadapter = new SimpleAdapter
                    (this, scanitems, R.layout.scan_list, SCAN_INFO_LIST, SCAN_INFO_LIST_RES);
            scan_list_info.setAdapter(scanadapter);
            Log.d(TAG," ---isRefreshing is "+swipeRefreshLayout.isRefreshing());
            if (swipeRefreshLayout.isRefreshing()) {
                Log.d(TAG,"-----isRefreshing");
                swipeRefreshLayout.setRefreshing(false);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        /*
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    scanitems=getScanInfo();
                    scanadapter.notifyDataSetChanged();
                    scan_list_info.setAdapter(scanadapter);
                    Log.d(TAG," ---isRefreshing is "+swipeRefreshLayout.isRefreshing());
                    if (swipeRefreshLayout.isRefreshing()) {
                        Log.d(TAG,"-----isRefreshing");
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },2000);*/

    }


    private ArrayList<HashMap<String, String>> getScanInfo(){
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        HashMap<String, String> item = null;
        try {
            Method method = wifi_service.getClass().getMethod("getWifiApConfiguration");
            wifiConfiguration = (WifiConfiguration) method.invoke(wifi_service);

            Method getscanlist = wifi_service.getClass().getMethod("getScanResults");
            List<ScanResult> scanlist = (List<ScanResult>) getscanlist.invoke(wifi_service);

            if(scanlist != null){
                int i;
                if(scanlist.size()>10) i=10;
                else i=scanlist.size()-1;
               for(;i>=0;--i){
                   final ScanResult scanResult = scanlist.get(i);
                   item = new HashMap<>();
                   item.put(SCAN_INFO_LIST[0], scanResult.SSID);
                   item.put(SCAN_INFO_LIST[1], String.valueOf(scanResult.level) +"dbm");
                   item.put(SCAN_INFO_LIST[2],String.valueOf(scanResult.capabilities));
                   list.add(item);
               }
            }
            Log.d(TAG, "----------davis scan list ");
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    private ArrayList<HashMap<String, String>> getInfo(WifiUtils mWifiUtils) {
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        HashMap<String, String> item = null;
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "connection status");
        item.put(WIFI_INFO_LIST[1], String.valueOf(wifi_service.isWifiEnabled()));
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "SSID");
        item.put(WIFI_INFO_LIST[1], wifiinfo.getSSID());
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "BSSID");
        item.put(WIFI_INFO_LIST[1], wifiinfo.getBSSID());
        list.add(item);

        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "Connection uptime");
        item.put(WIFI_INFO_LIST[1],wifiinfo.getLinkSpeed()<0 ? "0 s":
                                getNormalDHMSTime(WifiService.wifiUpTime));
        list.add(item);

        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "Siginal strength(RSSI)");
        item.put(WIFI_INFO_LIST[1], String.valueOf(wifiinfo.getRssi()));
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "Connection link rate");
        item.put(WIFI_INFO_LIST[1], String.valueOf(wifiinfo.getLinkSpeed()) + " Mbps");
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "Mac Address");
        item.put(WIFI_INFO_LIST[1], getWifiMacAddress());
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "IP Address/Mask");
        item.put(WIFI_INFO_LIST[1], int2ip(wifiinfo.getIpAddress()) + "/" + Formatter.formatIpAddress(dhcpinfo.netmask));
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "Gateway IP Address");
        item.put(WIFI_INFO_LIST[1], int2ip(dhcpinfo.gateway));
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "DNS IP Address");
        item.put(WIFI_INFO_LIST[1], int2ip(dhcpinfo.dns1) + "  " + int2ip(dhcpinfo.dns2));
        list.add(item);
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "Ntp server Address");
        item.put(WIFI_INFO_LIST[1], getNtpServerAddress());
        list.add(item);


        if(wifiConfigList!=null){
        for (WifiConfiguration wifiConfiguration : wifiConfigList) {
            String configSSid = wifiConfiguration.SSID;
            configSSid = configSSid.replace("\"", "");
            String currentSSid = wifiinfo.getSSID();
            currentSSid = currentSSid.replace("\"", "");
                if (currentSSid.equals(configSSid) && wifiinfo.getNetworkId() == wifiConfiguration.networkId) {
                    item = new HashMap<>();
                    item.put(WIFI_INFO_LIST[0], "Encryption mode");
                    item.put(WIFI_INFO_LIST[1], getSecurity(wifiConfiguration));
                    list.add(item);

                    item = new HashMap<>();
                    item.put(WIFI_INFO_LIST[0], "Connection mode");
                    item.put(WIFI_INFO_LIST[1], getWifiMode(wifiConfiguration));
                    list.add(item);
                }
            }
        }

        if(wifiConfigList!=null){
            for (WifiConfiguration wifiConfiguration : wifiConfigList) {
                String configSSid = wifiConfiguration.SSID;
                configSSid = configSSid.replace("\"", "");
                String currentSSid = wifiinfo.getSSID();
                currentSSid = currentSSid.replace("\"", "");
                if (currentSSid.equals(configSSid) && wifiinfo.getNetworkId() == wifiConfiguration.networkId) {
                    item = new HashMap<>();
                    item.put(WIFI_INFO_LIST[0], "Encryption mode");
                    item.put(WIFI_INFO_LIST[1], getWifiEnc(wifiConfiguration));
                    list.add(item);
                }
            }
        }



        /*
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0], "wifiConfiguration allowedKeyManagement");
        item.put(WIFI_INFO_LIST[1], wifiConfiguration.toString());
        list.add(item);
        */


        //blue tooth
        /*
        item = new HashMap<>();
        item.put(WIFI_INFO_LIST[0],"bluetooth status");
        item.put(WIFI_INFO_LIST[1],String.valueOf(bta.getState()));
        list.add(item);
        */
        return list;
    }

    private String getWifiMode(WifiConfiguration configuration){
        String mode="Unknown";
        try {
            String config = configuration.toString();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new ByteArrayInputStream(config.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
            String line;
            while ( (line = br.readLine()) != null ) {
                if(line.trim().startsWith("IP assignment:")){
                    return line.substring(14).trim();

                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return mode;
    }
    static String getSecurity(WifiConfiguration config) {
        String result="null";
        result= config.toString().trim();
        try {
            return result.substring(result.indexOf("KeyMgmt:")+8,result.indexOf("Protocols:"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;

    }
    private String getSecurity(){
        String security = "Unknown";
        try{
            Class<?> cls = Class.forName("com.android.settingslib.wifi.AccessPoint"); //class not found
            Constructor<?> constructor = cls.getConstructor(Context.class,wifiConfiguration.getClass());
            Method method = cls.getMethod("getSecurityString",boolean.class);
            Object accesspoint = constructor.newInstance(getApplicationContext(),wifiConfiguration);
            security = (String) method.invoke(accesspoint,true);
        }catch (Exception e){
            e.printStackTrace();
        }
        return security;
    }

    private String getWifiEnc(WifiConfiguration wifiConfiguration){
        try {
            String currentSSid = wifiinfo.getSSID();
            currentSSid = currentSSid.replace("\"", "");
            Method getscanlists = wifi_service.getClass().getMethod("getScanResults");
            List<ScanResult> scanlist = (List<ScanResult>) getscanlists.invoke(wifi_service);
            if(scanlist != null) {
                for (int i = scanlist.size() - 1; i >= 0; --i) {
                    final ScanResult scanResult = scanlist.get(i);
                    String scanSSid = scanResult.SSID;
                    scanSSid = scanSSid.replace("\"", "");
                    if (currentSSid.equals(scanSSid) && wifiinfo.getBSSID().equals(scanResult.BSSID)) {
                        String capabilities = scanResult.capabilities;
                        return capabilities;
                        /*
                        if(capabilities.contains("WPA2-") && capabilities.contains("WPA-")) {
                            return "WPA/WPA2";
                        } else if(capabilities.contains("WPA2-")) {
                            return "WPA2";
                        } else if(capabilities.contains("WPA-")){
                            return "WPA";
                        }else if(capabilities.contains("WEP")) {
                            return "WEP";
                        }*/
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "None";

    }

    public void sharedfile(){
        SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
        editor.putBoolean("simple_flag",true);
        editor.putString("name","Nothng");
        editor.commit();
    }


    /***************
     * context menu test  长按
     ************/

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        switch (v.getId()){
            case R.id.contextmenu_button:
                //menu.setHeaderTitle("Share to friends");
                getMenuInflater().inflate(R.menu.options_menu,menu);
                break;
            case R.id.contextmenu_tv:
                SubMenu colorSm = menu.addSubMenu(1, 1, 1, "color select");
                colorSm.add(2, 200, 201, "red");
                colorSm.add(2, 210, 211, "yellow");
                colorSm.add(2, 220, 221, "blue");

                menu.add(1, 2, 21, "设置画笔粗细");

                SubMenu widthSm = menu.addSubMenu(1, 3, 31, "设置画笔样式");
                widthSm.add(3, 300, 300, "线状画笔");
                widthSm.add(3, 301, 301, "填充画笔");

                menu.add(1, 4, 41, "清空画布");

                menu.add(1, 5, 51, "保存画布");

                menu.add(1, 6, 61, "退出应用");
                break;
            default:
                break;
        }
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_start_simpleActivity:
                Intent simpleActivity = new Intent();
                simpleActivity.setComponent(new ComponentName("com.sercomm.ott.mediaplayer",
                        "com.sercomm.ott.mediaplayer.SimpleActivity"));
                simpleActivity.putExtra("simple_flag",true);
                startActivity(simpleActivity);
                Toast.makeText(WifiActivity.this, "context menu click1,start SimpleActivity", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_start_videoViewActivity:
                Intent videoViewActivity = new Intent();
                videoViewActivity.setComponent(new ComponentName("com.sercomm.ott.mediaplayer",
                        "com.sercomm.ott.mediaplayer.VideoViewActivity"));
                startActivity(videoViewActivity);
                Toast.makeText(WifiActivity.this, "context menu click2,start VideoViewActivity", Toast.LENGTH_LONG).show();
                break;
            case R.id.menu_start_surfaceviewActivity:
                Intent surfaceViewActivity = new Intent();
                surfaceViewActivity.setComponent(new ComponentName("com.sercomm.ott.mediaplayer",
                        "com.sercomm.ott.mediaplayer.SurfaceViewActivity"));
                surfaceViewActivity.putExtra("imFlowsUrlStr","/sdcard/Movies/1.mp4");
                startActivity(surfaceViewActivity);
                break;
            case R.id.menu_start_showAppActivity:
                Intent showAppActivity = new Intent();
                showAppActivity.setComponent(new ComponentName("com.sercomm.ott.mediaplayer",
                        "com.sercomm.ott.mediaplayer.ShowAppActivity"));
                startActivity(showAppActivity);
                break;
            case R.id.menu_start_fragmentMainActivity:
                Intent fragementMainActivity = new Intent(WifiActivity.this,MainNewsActivity.class);
                startActivity(fragementMainActivity);
                break;
            case R.id.menu_start_viewpager:
                Intent viewPagerActivity = new Intent(WifiActivity.this,ViewPagerActivity.class);
                startActivity(viewPagerActivity);
                break;
            case R.id.menu_start_ottHtppTestActivity:
                Intent httpTestActivity = new Intent();
                httpTestActivity.setComponent(new ComponentName("com.sercomm.ott.mediaplayer",
                        "com.sercomm.ott.mediaplayer.OttHttpTestActivity"));
                startActivity(httpTestActivity);
                break;
            case R.id.menu_start_viewpager2:
                Intent viewPager2Activity = new Intent(WifiActivity.this,
                        com.sercomm.ott.mediaplayer.viewpager2.ViewPagerActivity.class);
                startActivity(viewPager2Activity);
                break;

            case 2:
            case 4:
            case 5:
            case 6:
            case 200:
            case 210:
            case 220:
            case 300:
            case 301:
                Toast.makeText(WifiActivity.this, "text context click" +
                        item.getItemId() + "/groupid " + item.getGroupId() + "/order " + item.getOrder(), Toast.LENGTH_LONG).show();
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return super.onContextItemSelected(item);
    }
    /************** end context menu test***********/



     /********** popup menu test************/
    @Override
    public void onClick(View v) {
        if (v == btn_popmenu) {
            Log.d(TAG, "---davis btn_popmenu click");
            pop.show();
        }
    }

    public void setPopupMenu(View v) {
        Log.d(TAG, "---davis setpopmenu");
        pop = new PopupMenu(this, v);
        getMenuInflater().inflate(R.menu.options_popmenu, pop.getMenu());
        pop.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.menu_dialog1:
                        SystemStatus.getVideoStatus();
                        dialog_test1();
                        //Toast.makeText(WifiActivity.this, "pop menu click1", Toast.LENGTH_LONG).show();
                        break;
                    case R.id.menu_dialog2:
                        dialog_test2();
                        //Toast.makeText(WifiActivity.this, "pop menu click2", Toast.LENGTH_LONG).show();
                        break;
                    case R.id.menu_start_wifi_service:
                        startService(myWifiService);
                        break;
                    case R.id.menu_stop_wifi_service:
                        stopService(myWifiService);
                        break;
                    default:
                }
                return false;
            }
        });
    }
    /**********end of popup menu test**********/


    /*********** menu test   按menu键时调用*****/
    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate( R.menu.options_menu, menu);
        Log.d(TAG,"------davis onCreateOptionsMenu");
        return super.onCreateOptionsMenu(menu);

       // super.onCreateOptionsMenu(menu);
        //menu.add(Menu.NONE,Menu.FIRST+1,0,"设置").setIcon(R.drawable.setting);
        //return true;

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) //得到被点击的item的itemId
       {
           case R.id.menu_setting:
               Toast.makeText(this,"click menu1",Toast.LENGTH_LONG).show();
               break;
           case R.id.menu_ok:
               Toast.makeText(this,"click menu ok",Toast.LENGTH_LONG).show();
               break;
           default:

       }
       // super.onOptionsItemSelected(item);
        //switch(item.getItemId()) //得到被点击的item的itemId
       // {
       //     case  Menu.FIRST+1 :  //对应的ID就是在add方法中所设定的Id
       //         Toast.makeText(WifiActivity.this,"onoptionsitemselected",Toast.LENGTH_LONG).show();
      //          break;
      //      case  Menu.FIRST+2 :
      //          break;
     //   }
     //   return true;

        return true;
    }
    */
    /***********end menu********/

    /***********
     * dialog test
     **********/
    private void dialog_test1() {
        AlertDialog.Builder ad = new AlertDialog.Builder(this);
        final String[] items = {"start gallery3d", "start mygallery3d", "myBroadcast"};
        ad.setTitle("Dialag test 1");
        ad.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                switch (i){
                    case 0:
                        Intent movieActivity = new Intent();
                        movieActivity.setComponent(new ComponentName("com.android.gallery3d",
                                "com.android.gallery3d.app.MovieActivity"));
                        movieActivity.setData(Uri.parse("/sdcard/Movies/1.mp4"));
                        startActivity(movieActivity);
                        break;
                    case 1:
                        Intent myMovieActivity = new Intent();
                        myMovieActivity.setComponent(new ComponentName("com.android.gallery3d",
                                "com.android.gallery3d.app.MovieActivity"));
                        ArrayList<String> play_list = new ArrayList<>();
                        play_list.add("/sdcard/Movies/1.mp4");
                        play_list.add("/storage/1110-1F5A/davis/demo/Wildlife.wmv");
                        play_list.add("/storage/1110-1F5A/davis/demo/adam_01_mpeg1_aac_1080p.mkv");
                        myMovieActivity.putExtra("playmode","contentreplay");
                        myMovieActivity.putStringArrayListExtra("playlist",play_list);
                        startActivity(myMovieActivity);
                        break;
                    case 2:
                        Intent myBroadCastIntent = new Intent("com.sercomm.ott.MY_BROADCAST");
                        sendBroadcast(myBroadCastIntent);
                        break;
                    default:
                        Toast.makeText(getApplicationContext(),"click item "+items[i],Toast.LENGTH_LONG).show();
                }
            }
        });
        ad.show();
    }
    private void dialog_test2(){
        AlertDialog.Builder ad = new AlertDialog.Builder(this);
        final String[] items={"items_1","items_2","items_3"};
        final int[] select={0};
        ad.setTitle("Dialog test 2");
        //ad.setIcon(R.drawable.setting);
        ad.setSingleChoiceItems(items,1,new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialogInterface,int i){
            select[0]= i;
            Toast.makeText(getApplicationContext(),"click "+items[i],Toast.LENGTH_SHORT).show();
            }
        });
        ad.setCancelable(true);
        ad.setPositiveButton("ok",new DialogInterface.OnClickListener(){
           @Override
            public void onClick(DialogInterface dialogInterface,int i){
                switch (select[0]){
                    case 0:
                        Toast.makeText(getApplicationContext(),"ok 111111",Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        Toast.makeText(getApplicationContext(),"ok 22222",Toast.LENGTH_LONG).show();
                        break;
                    case 2:
                        Toast.makeText(getApplicationContext(),"ok 33333",Toast.LENGTH_LONG).show();
                        break;
                    default:
                        Toast.makeText(getApplicationContext(),"ok "+select[0],Toast.LENGTH_LONG).show();
                }
           }
        });
        ad.setNegativeButton("cancel",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialogInterface,int i){
                Toast.makeText(getApplicationContext(),"cancel ",Toast.LENGTH_LONG).show();;
            }
        });
        ad.show();
    }

    /*********
     * dialog test end
     ********/

    /************** expandablelistview test***********/
    public void setListData(){
        Map<String, String> title_1 = new HashMap<String, String>();
        Map<String, String> title_2 = new HashMap<String, String>();
        title_1.put("group","clolr");
        title_2.put("group","object");
        groups.add(title_1);
        groups.add(title_2);

        Map<String, String> title_1_content_1 = new HashMap<String, String>();
        Map<String, String> title_1_content_2 = new HashMap<String, String>();
        Map<String, String> title_1_content_3 = new HashMap<String, String>();
        title_1_content_1.put("child","red");
        title_1_content_2.put("child","blue");
        title_1_content_3.put("child","yellow");
        List<Map<String, String>> childs_1 = new ArrayList<Map<String, String>>();
        childs_1.add(title_1_content_1);
        childs_1.add(title_1_content_2);
        childs_1.add(title_1_content_3);
        Map<String, String> title_2_content_1 = new HashMap<String, String>();
        Map<String, String> title_2_content_2 = new HashMap<String, String>();
        title_2_content_1.put("child","desk");
        title_2_content_2.put("child","computer");
        List<Map<String, String>> childs_2 = new ArrayList<Map<String, String>>();
        childs_2.add(title_2_content_1);
        childs_2.add(title_2_content_2);
        childs.add(childs_1);
        childs.add(childs_2);

        SimpleExpandableListAdapter sela = new SimpleExpandableListAdapter(
                this,groups,R.drawable.groups,new String[] {"group"},
                new int[] {R.id.textGroup},childs,R.drawable.childs,
                new String[] {"child"},new int[] {R.id.textChild}
        );
        expandableListView.setAdapter(sela);
        //setListAdapter(sela);

    }
    public void expandableFun(){
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition,
                                        int childPosition, long l) {
                Toast.makeText(
                        WifiActivity.this,
                        "您选择了"
                                + groups.get(groupPosition).toString()
                                + "子编号"
                                + childs.get(groupPosition).get(childPosition)
                                .toString(), Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener(){
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0, count = expandableListView.getCount(); i < count; i++) {
                    if(groupPosition!=i){
                        expandableListView.collapseGroup(i);
                    }
                }
            }
        });

    }
    /*
    @Override
    public boolean onChildClick(ExpandableListView parent,View v,
                                int groupPosition,int childPosition,long id) {
        Toast.makeText(
                WifiActivity.this,
                "您选择了"
                        + groups.get(groupPosition).toString()
                        + "子编号"
                        + childs.get(groupPosition).get(childPosition)
                        .toString(), Toast.LENGTH_SHORT).show();
        return super.onChildClick(parent, v, groupPosition, childPosition, id);
    }
    @Override
    public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) {
        return super.setSelectedChild(groupPosition, childPosition,
                shouldExpandGroup);
    }
    @Override
    public void setSelectedGroup(int groupPosition) {
        super.setSelectedGroup(groupPosition);
    }
    @Override

    public void onGroupExpand(int groupPosition) {
        for (int i = 0, count = getExpandableListAdapter().getGroupCount(); i < count; i++) {
            if(groupPosition!=i){
                getExpandableListView().collapseGroup(i);
            }
        }
    }*/

    /****************end expandablelistview test**********/



    public String[] NtpServers;
    public String getNtpServerAddress(){
        NtpServers = getResources().getStringArray(R.array.config_ntpServer_list);
        try {
            Class<?> sntpClass = Class.forName("android.net.SntpClient");
            Constructor<?> constructor = sntpClass.getConstructor();
            Object sntpObject = constructor.newInstance();
            Method getNtpServer = sntpObject.getClass().getDeclaredMethod("getNtpServer");
            String address = (String) getNtpServer.invoke(sntpObject);
            return address;
            /*
            Method reqtimeMethod = sntpClass.getMethod("requestTime", String.class, int.class);
            for ( int i=0; (NtpServers != null) && i<NtpServers.length; i++ ) {
                boolean ret = (boolean) reqtimeMethod.invoke(sntpObject, NtpServers[i], 3000);
                Log.d(TAG,"-----davis getNtpServerAddress "+ ret);
                if(ret){
                    return NtpServers[i];
                }
            }
            */
            //Method getNtpServer= sntpClass.getMethod("getNtpServer");
            //InetAddress address = (InetAddress)getNtpServer.invoke(sntpObject);
            //return address.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "null";
    }

    public String int2ip(long ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    public String getWifiMacAddress() {
        try {
            NetworkInterface nw = NetworkInterface.getByName("wlan0");
            byte[] addres = nw.getHardwareAddress();
            StringBuffer sb = new StringBuffer();
            if (addres != null && addres.length > 1) {
                sb.append(parseByte(addres[0])).append(":");
                sb.append(parseByte(addres[1])).append(":");
                sb.append(parseByte(addres[2])).append(":");
                sb.append(parseByte(addres[3])).append(":");
                sb.append(parseByte(addres[4])).append(":");
                sb.append(parseByte(addres[5]));
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "00:00:00:00:00:00";
    }


    private static String parseByte(byte b) {
        int intValue = 0;
        if (b >= 0) {
            intValue = b;
        } else {
            intValue = 256 + b;
        }
        return Integer.toHexString(intValue);
    }

    public String formatString(int value) {
        String strValue = "";
        byte[] ary = intToByteArray(value);
        for (int i = ary.length - 1; i >= 0; i--) {
            strValue += (ary[i] & 0xFF);
            if (i > 0) {
                strValue += ".";
            }
        }
        return strValue;
    }

    public byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }

    public static String getNormalDHMSTime(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;

        StringBuffer sb = new StringBuffer();
        if(day > 0) {
            sb.append(day+" days ");
        }
        if(hour > 0) {
            sb.append(hour+" h ");
        }
        if(minute > 0) {
            sb.append(minute+" m ");
        }
        if(second > 0) {
            sb.append(second+" s");
        }
        return sb.toString();
    }

    private void handleScanResultsAvailable() {
        if (Build.VERSION.SDK_INT >= 23) {
            Log.d(TAG, "-----------davis sdk int " + Build.VERSION.SDK_INT);
            //Settings.Secure.putInt(getContentResolver(),Settings.Secure.LOCATION_MODE, 1);
        }
        List<ScanResult> list = wifi_service.getScanResults();   //return null

        StringBuffer scanList = new StringBuffer();
        if (list != null) {
            for (int i = list.size() - 1; i >= 0; i--) {
                final ScanResult scanResult = list.get(i);

                if (scanResult == null) {
                    continue;
                }

                if (this.isEmpty(scanResult.SSID)) {
                    continue;
                }
                scanList.append(scanResult.SSID + " ");
            }
        }
        Log.d(TAG, "----------davis " + scanList);
        //mScanList.setText(scanList);
    }

    public static boolean isEmpty(CharSequence str) {
        return (str == null || str.length() == 0);
    }


    //bluetooth
    public String getBluetoothStatus() {
        if (bta != null && bta.isEnabled())
            return "";
        return "";
    }


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Wifi Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    @Override
    protected void onDestroy() {
        if(mWifiStateReceiver!=null) {
            unregisterReceiver(mWifiStateReceiver);
        }
        super.onDestroy();

    }

    @Override
    public void onWindowFocusChanged(boolean flag){
        Log.d(TAG,"------davis onWindowFocusChanged");
        if(!flag) {
            LinearLayout linearLayout = (LinearLayout) findViewById(R.id.wifi_test);
            linearLayout.setBackgroundColor(Color.GRAY);
            linearLayout.getBackground().setAlpha(100);
        }else {
            LinearLayout linearLayout = (LinearLayout) findViewById(R.id.wifi_test);
            linearLayout.setBackgroundColor(Color.BLACK);
        }
    }
    @Override
    public void onSaveInstanceState(Bundle outState){
        Log.d(TAG,"------davis enter onSaveInstanceState ");
        super.onSaveInstanceState(outState);
        outState.putString(KEY_ONSAVEINSTANCESTATE,"onSaveInstanceState");
    }
}
